<template>
  <div class="home-page">
    <!-- 头部 -->
    <el-card class="box-card" :body-style="{ padding: '10px', display: 'flex' }">
      <!--头像图片-->
      <el-avatar shape="square" class="avatarImg" :size="64">
        <img src="https://spring-oss.oss-cn-beijing.aliyuncs.com/images/img/avat.gif" alt="默认头像" />
      </el-avatar>
      <!--用户信息-->
      <div class="info-box">
        <h4>{{ }}</h4>
        <span>寄语：</span>
        <span>这个人很懒什么都没有留下</span>
      </div>
    </el-card>
    <!-- 订单数 -->
    <el-row :gutter="40">
      <el-col :span="8">
        <!--今日订单总数-->
        <el-card class="box-card" :body-style="{ padding: '5px', display: 'flex', alignItems: 'center' }" shadow="hover">
          <i class="el-icon-s-order"></i>
          <div>
            <h4>今日订单总数</h4>
            <span>1</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <!--今日销售总额-->
        <el-card class="box-card" :body-style="{ padding: '5px', display: 'flex', alignItems: 'center' }" shadow="hover">
          <i class="el-icon-bank-card"></i>
          <div>
            <h4>今日销售总额</h4>
            <span>11￥</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <!--昨日销售总额-->
        <el-card class="box-card" :body-style="{ padding: '5px', display: 'flex', alignItems: 'center' }" shadow="hover">
          <i class="el-icon-coin"></i>
          <div>
            <h4>昨日销售总额</h4>
            <span>1￥</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 待处理订单 -->
    <el-card class="box-card" :body-style="{ padding: '0px', textAlign: 'left' }" shadow="hover">
      <div class="clearfix">
        <span>待处理订单</span>
      </div>
      <el-row>
        <el-col :span="6" v-for=" (item, index) in list" :key="index">
          <div class="or" style=""><span>{{ index }}</span><span style="color: crimson;">({{ item }})</span></div>
        </el-col>
      </el-row>
    </el-card>
    <!-- 商品总览 -->
    <el-card class="box-card" :body-style="{ padding: '0px', textAlign: 'left' }" shadow="hover">
      <div class="clearfix">
        <span>商品总览</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="6">
          <div style="display: flex;flex-wrap: wrap; flex-direction: column;align-items: center;">
            <span style="color: black; font-size: 20px;padding: 5px; font-weight: 600;">全部商品</span>
            <el-statistic group-separator="," :value="product.length" suffix="件"
              :value-style="{ color: 'red', fontSize: '25px' }"></el-statistic>
          </div>
        </el-col>
        <el-col :span="6">
          <div style="display: flex;flex-wrap: wrap; flex-direction: column;align-items: center;">
            <span style="color: black; font-size: 20px;padding: 5px;font-weight: 600; ">已上架</span>
            <el-statistic group-separator="," :value="yes_sale" suffix="件"
              :value-style="{ color: 'red', fontSize: '25px' }"></el-statistic>
          </div>
        </el-col>
        <el-col :span="6">
          <div style="display: flex;flex-wrap: wrap; flex-direction: column;align-items: center;">
            <span style="color: black; font-size: 20px; padding: 5px; font-weight: 600;">已下架</span>
            <el-statistic group-separator="," :value="no_sale" suffix="件"
              :value-style="{ color: 'red', fontSize: '25px' }">
            </el-statistic>
          </div>
        </el-col>
        <el-col :span="6">
          <div style="display: flex;flex-wrap: wrap; flex-direction: column;align-items: center;">
            <span style="color: black; font-size: 19px;padding: 5px; font-weight: 600;">库存紧张</span>
            <el-statistic :value="stock.length" suffix="件"
              :value-style="{ color: 'red', fontSize: '25px' }"></el-statistic>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <!-- 订单统计 -->
    <el-card class="box-card" :body-style="{ padding: '0px', textAlign: 'left' }" shadow="hover">
      <div class="clearfix">
        <span>订单统计</span>
      </div>
      <el-row>

        <el-col :span="8" style="border-right: 1px solid black;">
          <!-- 定义图表外层容器 -->
          <div id="myHomeChart1" ref="homeEcharts1"></div>
        </el-col>
        <el-col :span="16">
          <!-- 定义图表外层容器 -->
          <div id="myHomeChart2" ref="homeEcharts2"></div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { getproduct, OrdersAll, product } from '@/api';
export default {
  name: 'KodaiAdminIndex',

  data () {
    return {
      product: [], yes_sale: 0, no_sale: 0, stock: 0, Orders: [], dai: 0, orgo: 0, y: 0, shippend: 0, pending: 0, re: 0, pr: 0, rr: 0
      , product_sort: [], ping: [], timers: ''
    };
  },
  // 组件销毁前调用
  beforeDestroy () {
    // 取消定时器
    clearInterval(this.timers)
  },
  mounted () {
    // 获得数据
    getproduct().then(res => {
      this.product = res.data.data
      this.is_sale = this.product.map(item => item.is_sale).flat();
      this.product_stock = this.product.map(item => item.product_stock).flat();
      this.stock = this.product_stock.filter(item => { return item < 50 })
      this.yes_sale = countOccurrences(this.is_sale, '1')
      this.no_sale = countOccurrences(this.is_sale, '2')
      this.product_sort = this.product.map(item => item.product_sort).flat().reduce((obj, item) => {
        if (obj[item]) {
          obj[item]++;
        } else {
          obj[item] = 1;
        }
        return obj;
      }, {});
      for (const key in this.product_sort) {
        let o = { value: this.product_sort[key], name: key }
        this.ping.push(o)
      }
      // 调用当前图表
      this.dataChart()
    }),
    
      OrdersAll().then(res => {
        this.Orders = res.data.data
        this.order_states = this.Orders.map(item => item.order_state).flat();
        this.dai = countOccurrences(this.order_states, '1')
        this.orgo = countOccurrences(this.order_states, '2')
        this.y = countOccurrences(this.order_states, '3')
        this.shippend = countOccurrences(this.order_states, '4')
        this.pending = countOccurrences(this.order_states, '5')
        this.re = countOccurrences(this.order_states, '6')
        this.pr = countOccurrences(this.order_states, '7')
        this.rr = countOccurrences(this.order_states, '8')
      })
    function countOccurrences (arr, val) {
      return arr.reduce((count, item) => {
        return count + (item === val ? 1 : 0);
      }, 0);
    }
    this.dataChart2()
  },

  methods: {
    // 绘制图表
    dataChart () {
      var AxisData = this.ping
      console.log();
      //初始化图表，this.$refs.homeEcharts获取到图表容器
      var myChart = this.$echarts.init(this.$refs.homeEcharts1)
      // 初始化配置
      var option = {
        legend: {  //配置图例组件
          left: 62,  //设置图例左边距
          top: 40,  //设置图例顶边距
          data: AxisData
        },
        toolbox: {  //配置工具箱组件
          show: true,  //设置工具箱组件是否显示
          left: 0,  //设置工具箱左边距
          top: 0,  //设置工具箱顶边距
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: {
              show: true,
              type: ['pie', 'funnel'],
              option: {
                funnel: {
                  x: '25%',
                  width: '50%',
                  funnelAlign: 'left',
                  max: 1548
                }
              }
            },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        calculable: true,
        series: [  //配置数据系列组件
          {
            type: 'pie',
            radius: '45%', //设置半径
            center: ['58%', '55%'],  //设置圆心
            clockWise: true,
            data: AxisData,
            label: {//显示文字
              show: true,
              //formatter:{a}--{b}  //格式化文字
              formatter: function (arg) {
                return arg.data.name + ":" + arg.percent + "%"
              },
              color: ['#F3DB5D', '#009AFF']
            },
          }
        ]
      };
      // 把参数配置放到容器里
      myChart.setOption(option)
    },
    // 绘制图表
    dataChart2 () {
      //初始化图表，this.$refs.homeEcharts获取到图表容器
      var myChart = this.$echarts.init(this.$refs.homeEcharts2)
      var dataOne = []
      var dataTwo = []
      var times = []
      times = (function () { // 立即执行函数
        let now = new Date();  // 获得当前的时间
        let res = []; // 存放时间的数组
        let len = 5; // 要存几个时间？
        while (len--) {
          res.unshift(now.toLocaleTimeString().replace(/^\D*/, '')); // 转换时间，大家可以打印出来看一下
          now = new Date(+now - 2000) // 延迟几秒存储一次？
        }
        return res;
      })();

      dataOne = (function () { // 5个随机数，
        let res = [];
        let len = 5;
        while (len--) {
          res.push(Math.round(Math.random() * 1000));
        }
        return res;
      })();
      dataTwo = (function () { // 5个随机数
        let res = [];
        let len = 5;
        while (len--) {
          res.push(Math.round(Math.random() * 1000));
        }
        return res;
      })();
      let options2 = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#283b56'
            }
          }
        },
        legend: {},
        xAxis: {
          type: 'category',
          data: times, // 把时间组成的数组接过来，放在x轴上
          boundaryGap: true
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: dataOne,
            type: 'line',
            name: '订单总数',
            smooth: true,
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: '平均值' }]
            }, areaStyle: {}
          },
          {
            data: dataTwo,
            name: '订单金额',
            type: 'line',
            smooth: true,
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: '平均值' }]
            }, areaStyle: {}
          }
        ]
      }
      function updateData () {
        let now = new Date();  // 获得当前的时间
        let res = []; // 存放时间的数组
        let len = 6; // 要存几个时间？
        while (len--) {
          res.unshift(now.toLocaleTimeString().replace(/^\D*/, '')); // 转换时间
          now = new Date(+now - 2000) // 延迟几秒存储一次？
        }
        return res;
      }
      async function getOrdersData () {
        const res = await OrdersAll();
        dataOne.shift();
        dataOne.push(parseInt(res.data.data.length) + Math.round(Math.random() * 80));
        dataTwo.shift();
        dataTwo.push(parseInt(res.data.data[res.data.data.length - 1].pay_price) + Math.round(Math.random() * 10));
      }
      this.timers = setInterval(async function () {
        times = updateData();
        await getOrdersData();
        myChart.setOption({
          xAxis: [
            {
              data: times
            }
          ],
          series: [
            {
              data: dataOne
            },
            {
              data: dataTwo
            }
          ]
        })
        // 把参数配置放到容器里

      }, 3000);
      myChart.setOption(options2)
    }


  },
  computed: {
    list () {
      return { '全部订单': this.Orders.length, '待付款订单': this.dai, '待发货订单': this.orgo, '已发货订单': this.shippend, '待确定收货订单': this.pending, '已完成订单': this.y, '待处理退货订单': this.re, '待处理退款订单': this.pr, '拒绝退货订单': this.rr }

    }
  }
};
</script>

<style lang="scss" scoped>
.home-page {
  margin: 0 3%;
  padding: 0px 10px 25px;
  min-height: 100%;
  user-select: none;
  // min-width: 1226px;
  background-color: #f6f8f9;

  .el-card {
    margin-top: 0.7rem;
    border: 1px solid #f6f8f9;

    .clearfix {
      background-color: #f2f6fc;
      padding: 10px !important;
      font-weight: bold;
    }

    i {
      color: #20a0ff;
      font-size: 72px;
    }
  }

  .el-statistic .head .title {
    color: #000 !important;
  }
}

.text {
  display: flex;
}

.or {
  padding: 2%;
  border-bottom: 1px solid black;
  margin: 4%;
  display: flex;
  justify-content: space-between;
}

/* 给图表容器定义宽高 */
#myHomeChart1 {
  width: 400px;
  height: 400px;
}

#myHomeChart2 {
  width: 800px;
  height: 400px;
}
</style>